using System;
using CKS.EBE.API;
using Microsoft.SharePoint;
using System.Xml;
using System.Diagnostics;

namespace CKS.EBE.WebControls
{
    public class CategoriesList : List
    {
        private bool _IncludePostCount;

        /// <summary>
        /// is false if not specified
        /// </summary>
        public bool IncludePostCount
        {
            get { return _IncludePostCount; }
            set { _IncludePostCount = value; }
        }

        public CategoriesList()
        {
            ListName = Localization.GetListName(Localization.BlogList.Categories, Web.Language);
        }

        protected override XmlDocument BuildDocument()
        {
            try
            {
                XmlDocument oDoc = base.BuildDocument();

                if (IncludePostCount)
                {
                    // get posts list only once
                    SPList posts = Helper.GetListByFolderName(Web, Localization.GetListName(Localization.BlogList.Posts, Web.Language));

                    XmlNodeList oCats = oDoc.SelectNodes("rows/row");

                    if (oCats != null)
                    {
                        foreach (XmlElement oCat in oCats)
                        {
                            int iCount = CalculatePostCount(oCat.SelectSingleNode("Title").InnerText, posts);
                            oCat.SetAttribute("PostCount", iCount.ToString());
                        }
                    }
                }

                return oDoc;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);

                var oError = new XmlDocument();
                oError.LoadXml(string.Format("<Error>{0}</Error>", ex.Message));
                return oError;
            }
        }

        private static int CalculatePostCount(string categoryTitle, SPList posts)
        {
            // find items with the specified category
            var oQuery = new SPQuery
                             {
                                 ViewFields = "<FieldRef Name='Categories'/>",
                                 Query = string.Format("<Where><Eq><FieldRef Name='Categories'/><Value Type='Text'>{0}</Value></Eq></Where>", categoryTitle)
                             };

            return posts.GetItems(oQuery).Count;
        }
    }
}
